import send_msg from '@feidao-factory/send-msg';
import config from '@feidao-factory/send-msg/nodejs/config';

const DBACC_FIND = 'dbacc.find.intranet';
const spaceid = config.spaceid;

interface IQueryParam {
	spaceid: string;
	sql: string;
	systemid: string;
}

interface IQueryResult {
	query_mode: 1;
	spaceid: string;
	systemid: string;
	tablename: string;
	dataArray: any;
}

/**
 * sql语句查询服务
 * @param action_id 系统参数action_id
 * @param session_id 系统参数sessionid
 * @param systemid 项目的systemid
 */
export default function sql_query(action_id: string, session_id: string, systemid: string) {
	let params = [] as IQueryParam[];

	function prepare(sql: string) {
		params.push({
			query_mode: 2,
			spaceid,
			sql,
			systemid,
			tablename: ''
		} as IQueryParam);
	}

	async function exec() {
		const data = await (send_msg(action_id, session_id, DBACC_FIND, params) as Promise<IQueryResult[]>);
		params = [];
		return data.map((d) => {
			return d.dataArray;
		});
	}

	return {
		exec,
		prepare
	};
}
